package com.yifeng.shiro.filter;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

public class CrmPermissionsAuthorizationFilter
	extends PermissionsAuthorizationFilter {

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
		 Subject subject = getSubject(request, response);
	        // If the subject isn't identified, redirect to login URL
	        if (subject.getPrincipal() == null) {
	            saveRequestAndRedirectToLogin(request, response);
	        } else {
	        	
	        	HttpServletRequest req = (HttpServletRequest) request;
	        	HttpServletResponse resp = (HttpServletResponse) response;
	        	//区分是否是AJax请求
	        	String xRequestedWith = req.getHeader("X-Requested-With");
	        	if (StringUtils.hasLength(xRequestedWith)&&"XMLHttpRequest".equals(xRequestedWith)) {
	        		resp.setContentType("text/json; charset=UTF-8");
	        		resp.getWriter().print("{\"success\":false,\"message\":\"未登录\"}");
				}else{
					  // If subject is known but not authorized, redirect to the unauthorized URL if there is one
		            // If no unauthorized URL is specified, just return an unauthorized HTTP status code
		            String unauthorizedUrl = getUnauthorizedUrl();
		            //SHIRO-142 - ensure that redirect _or_ error code occurs - both cannot happen due to response commit:
		            if (StringUtils.hasText(unauthorizedUrl)) {
		                WebUtils.issueRedirect(request, response, unauthorizedUrl);
		            } else {
		                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
		            }
				}
	          
	        }
	        return false;
	}

	
}
